package com.newcoder.community.controller;

import com.newcoder.community.annotation.LoginRequired;
import com.newcoder.community.pojo.LoginTicket;
import com.newcoder.community.pojo.User;
import com.newcoder.community.serverce.LikeService;
import com.newcoder.community.serverce.LoginTicketService;
import com.newcoder.community.serverce.UserService;
import com.newcoder.community.utill.CommunityUtill;
import com.newcoder.community.utill.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.ls.LSException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${commnuity.path.upload}")
    private String uploadPath;
    @Value("${commnuity.path.domain}")
    private String domain;
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LoginTicketService loginTicketService;
    @Autowired
    private LikeService likeService;

    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage() {
        return "/site/setting";
    }

    @LoginRequired

    @PostMapping("/upload")
    private String uploadHeader(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片");
            return "/site/setting";
        }
        String filename = headerImage.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式不正确");
        }
        filename = CommunityUtill.generateUUID() + suffix;
        File dext = new File(uploadPath + "/" + filename);
        try {
            headerImage.transferTo(dext);
        } catch (IOException e) {
            logger.error("上传文件失败" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器发生异常", e);
        }
        User user = hostHolder.getUser();
        String url = domain + "/user/header/" + filename;
        userService.updateHeader(user.getId(), url);
        return "redirect:/index";
    }

    @GetMapping("/header/{filename}")
    public void getHeader(@PathVariable("filename") String filename, HttpServletResponse resp) {
        String suffix = filename.substring(filename.lastIndexOf("."));
        filename = uploadPath + "/" + filename;
        resp.setContentType("/image" + suffix);

        try (
                FileInputStream fis = new FileInputStream(filename);
                ServletOutputStream os = resp.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败" + e.getMessage());
        }
    }

    @PostMapping("/update")
    public String updatePassword(
            @CookieValue("ticket") String ticket
            , String oldPassWord
            , String newPassWord1, String newPassWord2
            , Model model) {
        if (oldPassWord == null) {
            model.addAttribute("oldpassworderror", "请输入密码");
            return "/site/setting";
        }
        LoginTicket loginTicket = loginTicketService.selectByTicket(ticket);
        int userId = loginTicket.getUserId();
        User user = userService.selectById(userId);
        System.out.println(CommunityUtill.md5(oldPassWord));
        if (!user.getPassword().equals(CommunityUtill.md5(oldPassWord) + user.getSalt())) {
            model.addAttribute("oldpassworderror", "原密码错误请重新输入");
            return "/site/setting";
        }
        if (newPassWord1 == null) {
            model.addAttribute("newpassworderror", "新密码不能为空");
        }
        if (!newPassWord1.equals(newPassWord2)) {
            model.addAttribute("checkpassword", "输入两次密码不同");
            return "/site/setting";
        }
        userService.updatePassword(userId, CommunityUtill.md5(newPassWord1) + user.getSalt());
        hostHolder.clean();
        return "/site/login";
    }
    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId,Model model){
        User user = userService.selectById(userId);
        if(user==null){
            throw  new RuntimeException("该用户不存在");
        }
        model.addAttribute("user",user);
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount",likeCount);
        return  "/site/profile";

    }
}
